package org.create.builder;

import org.create.utils.IoTool;
import org.create.utils.LogTool;

import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;

import static org.create.bean.Constants.*;


public class BuildApplication {
    private static BufferedWriter bw;

    private static void buildPackageComment() throws IOException {
        bw.write("package " + PACKAGE_BASE + ";");
        appendLine(2);
        bw.write("import org.mybatis.spring.annotation.MapperScan;");
        appendLine();
        bw.write("import org.springframework.boot.SpringApplication;");
        appendLine();
        bw.write("import org.springframework.boot.autoconfigure.SpringBootApplication;");
        appendLine(3);
    }

    private static void buildClassComment() throws IOException {
        bw.write("@SpringBootApplication");
        appendLine();
        bw.write("@MapperScan(basePackages = {\"" + PACKAGE_BASE + "." + PACKAGE_MAPPERS + "\"})");
        appendLine();
        bw.write("public class Application {");
        appendLine();
        bw.write("    public static void main(String[] args) {");
        appendLine();
        bw.write("        SpringApplication.run(Application.class, args);");
        appendLine();
        bw.write("    }");
        appendLine();
        bw.write("}");
        appendLine();
    }

    private static void appendLine() throws IOException {
        appendLine(1);
    }

    private static void appendLine(int loop) throws IOException {
        if (loop == 1) {
            bw.newLine();
        } else {
            for (int i = 0; i < loop; i++) {
                bw.newLine();
            }
        }
    }

    public static void run() {

        File file = new File(PATH_BASE_JAVA + "Application" + JAVA_SUFFIX);
        File dir = file.getParentFile();
        boolean d = dir.mkdirs();
        LogTool.printLog(d, "新建目录", dir);
        try {
            boolean r = file.createNewFile();
            LogTool.printLog(r, "新建文件", file);
            bw = IoTool.createBw(file);
            buildPackageComment();
            buildClassComment();
        } catch (Exception e) {
            LogTool.printError(e);
        } finally {
            IoTool.close();
        }
    }
}

